package park

import (
	"fmt"
	"math"
	"parking-lot-go-dingding/controller"
	"parking-lot-go-dingding/model"
	"strconv"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {

	requestStruct := struct {
		Keywords    string `json:"keywords"`
		Latitude    string `json:"latitude"`
		Limit       int    `json:"limit"`
		Longitude   string `json:"longitude"`
		Page        int    `json:"page"`
		ParkingType int    `json:"parking_type"`
		Sort        int    `json:"sort"`
		SortParams  string `json:"sort_params"`
	}{}

	//接收加密串
	if err := c.ShouldBindJSON(&requestStruct); err != nil {
		controller.Fail(c, "json接收失败"+err.Error())
		return
	}

	start := (requestStruct.Page - 1) * requestStruct.Limit

	var parkingLotStruct model.ParkingLotStruct
	parkLots, count, err := parkingLotStruct.SearchAndCount(requestStruct.Longitude, requestStruct.Latitude, requestStruct.Sort, start, requestStruct.Limit, requestStruct.ParkingType, requestStruct.Keywords, requestStruct.SortParams)
	if err != nil {
		controller.Fail(c, "停车场获取失败"+err.Error())
		return
	}

	var longitude float64
	var latitude float64
	parkReturn := make([]map[string]interface{}, 0)

	for k, v := range parkLots {
		if k == 0 {
			longitude = v.Longitude
			latitude = v.Latitude - 0.02
		}


		parkType := "未知"
		switch v.PType {
		case 1:
			parkType = "路内"
		case 2:
			parkType = "路外"
		}

		distanceType := "米"
		distance, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", float64(v.Distance)/1000), 64)
		if distance > 1000 {
			distanceType = "千米"
		}

		parkReturn = append(parkReturn, map[string]interface{}{
			"address":        v.Address,
			"clicks":         v.Clicks,
			"distance":       distance,
			"distance_type":  distanceType,
			"free_minutes":   v.FreeMinutes,
			"id":             v.Id,
			"latitude":       v.Latitude,
			"longitude":      v.Longitude,
			"m_time":         v.MTime,
			"much_id":        v.MuchId,
			"name":           v.Name,
			"p_type":         parkType,
			"park_city":      v.ParkCity,
			"park_code":      v.ParkCode,
			"parking_number": v.ParkingNumber,
			"region_code":    v.RegionCode,
			"region_name":    v.RegionName,
			"sort":           v.Sort,
			"state":          v.State,
			"stop_type":      v.StopType,
		})
	}

	controller.Success(c, map[string]interface{}{
		"list":         parkReturn,
		"current_page": requestStruct.Page,
		"last_page":    math.Ceil(float64(count) / float64(requestStruct.Limit)),
		"lat":          latitude,
		"lon":          longitude,
	})
}
